Home |
| Latest | About | Random
# Week 7 Monday and Friday Dear Class, This week we start discussing **Section 15 on structs and classes.** This is how we can create our own data type! It is a powerful programming paradigm called "*object oriented programming*" (OOP), where we think of things as "objects" that have "data" and "methods". (Two other paradigms are *procedural programming* and *functional programming*. Practical programming uses a mixture of all of these.) Pedagogically, we will first learn about `struct`s, and then `class`es, which really have only "some technical differences". **To not fall behind, please read up to section 15.3 after midterm 2. We will pick up the rest of section 15 after we return from midterm 2.** Again, **Midterm 2 is next Monday 11/16 in class (Week 8)**. - An old exam from the past is posted on BruinLearn. Our exam is not necessarily going to be exactly like it, but it is good practice. Please review the problems in the text and notes as well. - Another document *midterm_2_advice.pdf* is also posted on BruinLearn, which tells you which sections in the text you can safely skip. - See email announcement (found on BruinLearn) to see a list of topics that you are responsible for. - **Please bring your Bruin ID card to the exam.** Through discussion with some of you, here's a list of general advice for coding exams. - Pay attention to data type. - Keep track of the value a variable is currently holding. - Pay attention to indexing of string (and later vector). - Strive to have an exact understanding or a good model of how various functions or features would work in our program. - Find a organization scheme to keep track of (1) where you are in the program, (2) which scope you are in, and (3) what are the values to the data variables we have. - Line by line and follow the control flow! - Certain tips and tricks may have been given in class, discussion, notes, or textbook. So pay attention to those! **You got this! Stay healthy, get enough rest, drink lots of water, eat fruits and veggies and vitamin C. Also, wear a mask if you can if you are coughing.** -- B. . . . . . **Now...let's make some monsters and do...** ## MONSTER BATTLE!!!! **Designing `struct` as a custom data container, constructing instances of a `struct`, and member variables.** Let's create some `Monster`s, say for a video game! Well, what should we know about a `Monster`? - `name` for its name, as a `string` - `species` for its species, as a `string` - `life` for how much life it has, as an `int` - `power` for how much power it has, as an `int` - `armor` for how much armor it has, as an `int` Say, we have `Monster`s named Bob, Dylan, and Justin below: ![[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 03.12.05.excalidraw.svg]] %%[[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 03.12.05.excalidraw.md|🖋 Edit in Excalidraw]]%% . . . . . How do we store these data for all these `Monster`s? Seems like we need a *container* for this `Monster` type! In C++ we can design such a container called `struct`. So let us create a `struct` for `Monster`s. ```cpp #include #include using namespace std; struct Monster {}; // note the semicolon after the } int main() { return 0; } ``` That's it! That declares and defines a new data type `Monster`! That was easy! . . . . . Well ok, this `Monster` current doesn't seem to have anything. So let us write to the inside of `{}` of this `struct`, to tell it that we want it to hold some data, or **member variables**. In our case, `name`, `species`, `life`, `power`, and `armor` for our `Monster`. We declare the variables with their appropriate types as usual: ```cpp #include #include using namespace std; struct Monster { string name, species; // member variables int life, power, armor; }; // note the semicolon after the } int main() { return 0; } ``` . . . . . This gives a *blueprint* for the `Monster` data type. In order to actually use it, we need to construct **instances** of it. Let us construct three instances of the `Monster` `struct`, with identifiers (variable name) `bob`, `dylan`, and `justin`. ```cpp #include #include using namespace std; struct Monster { string name, species; // member variables int life, power, armor; }; // note the semicolon after the } int main() { Monster bob; // instances of Monster Monster dylan; Monster justin; return 0; } ``` This is similar to how we create an `int` variable like `int x`, or a `double` like `double y`. We can also create them in one line like `Monster bob, dylan, justin;` These are default constructed. Note that the `string` members start out empty, but the `int` members are left **uninitialized** (they hold garbage values) until we set them! Now, each `Monster` instance has **member variables** `name`, `species`, `life`, `power`, and `armor`, which we can access by using the **member access operator** `.` between the variable name and the member variables. We can set them and use them as so: ```cpp #include #include using namespace std; struct Monster { string name, species; // member variables int life, power, armor; }; // note the semicolon after the } int main() { Monster bob, dylan, justin; bob.name = "Bob"; bob.species = "Goblin"; bob.life = 30; bob.power = 3; bob.armor = 1; dylan.name = "Dylan"; dylan.species = "Dragon"; dylan.life = 100; dylan.power = 20; dylan.armor = 20; justin.name = "Justin"; justin.species = "Human"; justin.life = 50; justin.power = 10; justin.armor = 5; return 0; } ``` Think of each as a container for some `Monster` data! ![[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 07.48.49.excalidraw.svg]] %%[[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 07.48.49.excalidraw.md|🖋 Edit in Excalidraw]]%% Each member has its own type and associated operations, which we can use as usual. For example ```cpp cout << dylan.species << endl; cout << dylan.species.length() << endl; cout << justin.power + bob.power << endl; ``` Soon, as we will see, like the `string` and `vector` class, a `struct` can be more than a data container, as it can also have member functions ("methods"). . . . . . ## Constructor: A first look. **Constructor function and member initializer list.** Setting each member value for each `Monster` like above is a bit cumbersome. Recall how for `string` or `vector` we could create like this ```cpp string s(10, '!'); // a string that contains "!!!!!!!!!!" vector v(3, 7); // a vector that has {7, 7, 7} ``` We'd like to construct a `Monster` in one line too. We do this by using the **constructor function** of the `Monster` `struct`, which is called the same name `Monster`, like so ```cpp struct Monster { string name, species; // member variables int life, power, armor; Monster (string _name) : name(_name) {} }; ``` Here `Monster (string _name)` says, when we construct a `Monster` `struct`, we should specify a `string` to pass into the parameter `_name`. The part from the colon `:` to the definition brace `{}` is called the **member initializer list**. So `name(_name)` means initialize the member value `name` with the value of the parameter `_name`. So doing ```cpp Monster z("Johnny"); ``` constructs a `Monster z` whose member `z.name` is set to be `"Johnny"`. Any additional actions to be taken at construction go into the body `{}` of the constructor function. We can of course specify more members to be initialized, by adding to the parameter list of the constructor function, as well as the member initializer list. In general, `: value1(param1), value2(param2), value3(param3)` sets the member values `value1`, `value2`, and `value3` to the parameters `param1`, `param2`, and `param3` respectively. So we can do something like this for our `Monster`: ```cpp struct Monster { string name, species; // member variables int life, power, armor; Monster (string _name, string _species, int _life, int _power, int _armor) : name(_name), species(_species), // don't forget : life(_life), power(_power), armor(_armor) {} }; ``` In general, for `struct MyClass`, its constructor function looks like ```cpp MyClass (T1 p1, T2 p2, T3 p3) : v1(p1), v2(p2), v3(p3) { // additional code to be executed at construction } ``` where member value `v1` is initialized to `p1`, and so on. So now we can construct our `Monster`s like so ```cpp Monster bob("Bob", "Goblin", 30, 3, 1); Monster dylan("Dylan", "Dragon", 100, 20, 20); Monster justin("Justin", "Human", 50, 10, 5); ``` Of course, one would need to know which position refers to which! This is where documentation of our struct later would be good. But this is similar to the case of string and vector, we would need to know the constructor patterns. Note, by having a constructor function like that, we will have to specify each of those parameters, otherwise we get a build error! We can no longer have default construction, **unless we also specify it by function overloading!** For example we can overload it with `Monster() {}`. Otherwise we would get a build error, where a constructor expects some arguments when none is provided. So we can overload it like this ```cpp struct Monster { string name, species; // member variables int life, power, armor; Monster (string _name, string _species, int _life, int _power, int _armor) : name(_name), species(_species), life(_life), power(_power), armor(_armor) {} Monster () {} }; ``` in case a `Monster` is created where no argument is given. As before, the `int` members of such a `Monster` are left uninitialized until we set them. We can add additional actions to be taken in the constructor definition body `{}`. Like so ```cpp struct Monster { string name, species; // member variables int life, power, armor; Monster (string _name, string _species, int _life, int _power, int _armor) : name(_name), species(_species), life(_life), power(_power), armor(_armor) { cout << "A monster called " << name << " is created!" << endl; } Monster () { cout << "An unknown monster is created!" << endl; } }; ``` . . . . . ## Doing things to monsters, or having monsters do things! **Member functions.** Let us write a function that prints out the information stored in a `Monster`, called `print` ```cpp void print(const Monster& monster) { cout << monster.name << " (" << monster.species << ") " << "Life: " << monster.life << " | " << "Powr: " << monster.power << " | " << "Armr: " << monster.armor << endl; } ``` Do you see why we make the choice of passing it by reference to const here? . . . . . Ok this is neat. But we can make each instance of the `Monster` call its own **member function** to print it. We first have to write it of course! We will write a member function called `print` as well. ```cpp struct Monster { string name, species; int life, power, armor; Monster (string _name, string _species, int _life, int _power, int _armor) : name(_name), species(_species), life(_life), power(_power), armor(_armor) {} Monster () {} void print() const { // a member function ! cout << name << " (" << species << ") " << "Life: " << life << " | " << "Powr: " << power << " | " << "Armr: " << armor << endl; } }; ``` A few differences between the free function `print` and this member function `Monster::print` (this is the full name of this member function, `::` is the scope resolution operator). - location of the `const` keyword in the definition. - For the free function `print`, we simply pass by reference to const, `print(dylan)`. - For the member function `Monster::print`, we just call it `dylan.print()` - We didn't pass in a `Monster&` - Somehow the member function `Monster::print` knows about the variables `name`, `species`, `life`, `power`, `armor`. To understand this, we shall look at a diagram of what happens when you call a member function from this `struct Monster`. When you run `dylan.print()`, a function scope is created and an **implicit parameter** (let us call it `self` as in the book) is created, with the **implicit argument** `dylan` passed in as reference! And because `Monster::print` has a `const` between `()` and `{}`, this implicit parameter is passed in by *reference to const*. (In actual C++, the implicit parameter is named `this`, and it is a *pointer* rather than a reference, but thinking of it as a reference called `self` is a good model for now.) Here is a diagram of the member function call `dylan.print()` ![[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 07.54.08.excalidraw.svg]] %%[[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 07.54.08.excalidraw.md|🖋 Edit in Excalidraw]]%% So by following the arrow, we see `Monster::print` can now access `dylan`'s member variables `name`, `species`, `life`, `power`, and `armor`. After the body of this member function `Monster::print` is done executing, the scope is destroyed as usual. . . . . . Ok. Let us write a function to determine how much damage a `Monster` will take when dealt a `raw` amount. - Say the damage that a `Monster` takes is the greater of `raw - armor` and `1`, where `raw` is the raw damage dealt, and `armor` is the `Monster`'s own armor - Example: `dylan` has `power` of `20`, and `bob` has `armor` of `1`. So if `dylan` attacks `bob`, `bob` would take `max(20 - 1, 1) = 19` damage. - Example: `bob` has `power` of `3`, and `dylan` has `armor` of `20`. So if `bob` attacks `dylan`, `dylan` would take `max(3 - 20, 1) = 1` damage. - Let us call this member function `damage_to_take` ```cpp #include struct Monster { string name, species; int life, power, armor; Monster (string _name, string _species, int _life, int _power, int _armor) : name(_name), species(_species), life(_life), power(_power), armor(_armor) {} Monster () {} void print() const { cout << name << " (" << species << ") " << "Life: " << life << " | " << "Powr: " << power << " | " << "Armr: " << armor << endl; } int damage_to_take(int raw) const { return max(raw - armor, 1); } }; ``` Let us analyze what happens when we call the member function `Monster::damage_to_take` by `dylan.damage_to_take(10)` ![[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 08.36.47.excalidraw.svg]] %%[[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 08.36.47.excalidraw.md|🖋 Edit in Excalidraw]]%% Let us write a member function `Monster::take_damage` to reduce the `life` of the `Monster` by deducting the damage number from its `life`, but be no less than `0`. ```cpp #include struct Monster { string name, species; int life, power, armor; Monster (string _name, string _species, int _life, int _power, int _armor) : name(_name), species(_species), life(_life), power(_power), armor(_armor) {} Monster () {} void print() const { cout << name << " (" << species << ") " << "Life: " << life << " | " << "Powr: " << power << " | " << "Armr: " << armor << endl; } int damage_to_take(int raw) const { return max(raw - armor, 1); } void take_damage(int dmg) { life = max(life - dmg, 0); } }; ``` Here the implicit parameter `self` is not going to be `const` anymore, as we will modify its member value! Here is a diagram for when we call `dylan.take_damage(10)` ![[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 08.47.29.excalidraw.svg]] %%[[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 08.47.29.excalidraw.md|🖋 Edit in Excalidraw]]%% Finally, let us write a member function `Monster::strike` where our `Monster` strikes another `Monster`, according to above rules! ```cpp #include struct Monster { string name, species; int life, power, armor; Monster (string _name, string _species, int _life, int _power, int _armor) : name(_name), species(_species), life(_life), power(_power), armor(_armor) {} Monster () {} void print() const { cout << name << " (" << species << ") " << "Life: " << life << " | " << "Powr: " << power << " | " << "Armr: " << armor << endl; } int damage_to_take(int raw) const { return max(raw - armor, 1); } void take_damage(int dmg) { life = max(life - dmg, 0); } void strike (Monster& target) const { target.take_damage(target.damage_to_take(power)); cout << name << " struck " << target.name << "!" << endl; } }; ``` So let's see what happens when we call `dylan.strike(bob)`. Note. **Arguments are evaluated before the call happens** - So we first perform `target.damage_to_take(power)` - Then take that value and pass it into `target.take_damage`. ![[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 09.01.35.excalidraw.svg]] %%[[1-teaching/ucla-2026-fall-pic-10a/---files/Week-7-Monday 2026-11-09 09.01.35.excalidraw.md|🖋 Edit in Excalidraw]]%% ## Constructor function, revisited. How do constructor functions work then? In our `Monster` `struct`, we have a constructor function also named `Monster`. Its technical name is actually `Monster::Monster` (like member functions). So what happens when we call `Monster bob("Bob", "Goblin", 30, 3, 1)`? Since one of the overloads of `Monster::Monster` has signature `Monster::Monster(string name, string species, int life, int power, int armor)`, passing in five arguments for `bob` will call upon this overload. Now this overload also came with a **member initializer list** ```cpp Monster (string _name, string _species, int _life, int _power, int _armor) : name(_name), species(_species), life(_life), power(_power), armor(_armor) { // possibly some code to be executed. } ``` which we say would assign the appropriate member values. So what exactly happens when `Monster bob("Bob", "Goblin", 30, 3, 1)` is called? First some space is reserved in memory for a `Monster` called `bob`. And the order of the member variables are declared in the struct interface is the order they appear in memory. (For `Monster`, it is `name, species life, power, armor`.) Then a scope is introduced. - The implicit parameter `self` is created, and it references the newly created instance of `Monster` called `bob`. - The explicit parameter variables are created in this scope. So `_name, _species, _life, _power, _armor` are created in scope. - The explicit arguments are assigned to the explicit parameters. So assign `"Bob", "Goblin", 30, 3, 1` to `_name, _species, _life, _power, _armor`/ Now we process the member initializer list. - `name(_name)` means initialize the member variable `name` using the value of the parameter `_name`. - `species(_species)` means initialize the member variable `species` using the value of the parameter `_species`. - `life(_life)` means initialize the member variable `life` using the value of the parameter `_life`. - `power(_power)` means initialize the member variable `power` using the value of the parameter `_power`. - `name(_armor)` means initialize the member variable `armor` using the value of the parameter `_armor`. Finally, if there is any code in the function body, then those code execute. When the code in the body is done executing, the scope is destroyed. - - - - - ## Practice. For practice. create a `struct` called `Point`, which is meant to contain the `x` and `y` coordinate of a point on the Cartesian plane. Let us also write constructors for `Point`, where one we initialize both `x` and `y` coordinates directly, and we also write a default constructor where it initializes to `(x,y) = (0,0)`. As for member functions, let us write a `Point::print` to print out the coordinates, a `Point::scale` to scale the coordinates by some factor `k`, and a `Point::distance_to` to calculate the distance of this `Point` to another `Point`.